package com.orie.librarybase.net.CookieUtils;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import com.orie.librarybase.BaseApplication;
import com.orie.librarybase.utils.UserUtils;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by 吕冬冬 on 2019.05.09.
 *
 * @auhtor 吕冬冬
 * email 863964634@qq.com
 * 内容:
 * 修改人：
 * 修改时间：
 * 修改备注：
 */

public class MyInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        if (request.method().equals("GET")) {
            request = addGetParams(request);
        } else if (request.method().equals("POST")) {
            request = addPostParams(request);
        }
        return chain.proceed(request);

    }


    //get请求 添加公共参数 签名
    private static Request addGetParams(Request request) {
        //添加公共参数
        long time = System.currentTimeMillis() / 1000;
        HttpUrl httpUrl = request.url()
                .newBuilder()
                .addQueryParameter("accesstoken", UserUtils.getToken(BaseApplication.getContext()))
                .build();
        request = request.newBuilder().url(httpUrl).build();
        return request;
    }


    //post 添加签名和公共参数
    private Request addPostParams(Request request) {
        if (request.body() instanceof FormBody) {
            FormBody.Builder bodyBuilder = new FormBody.Builder();
            FormBody formBody = (FormBody) request.body();

            //把原来的参数添加到新的构造器，（因为没找到直接添加，所以就new新的）
            for (int i = 0; i < formBody.size(); i++) {
                bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i));
            }
            long time = System.currentTimeMillis() / 1000;
            formBody = bodyBuilder
                    .addEncoded("accesstoken", UserUtils.getToken(BaseApplication.getContext()))
                    .build();
            request = request.newBuilder().post(formBody).build();
        } else if (request.body() instanceof MultipartBody) {
            MultipartBody.Builder bodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
            MultipartBody formBody = (MultipartBody) request.body();

            //把原来的参数添加到新的构造器，（因为没找到直接添加，所以就new新的）
            for (int i = 0; i < formBody.size(); i++) {
                bodyBuilder.addPart(formBody.part(i));
            }
            long time = System.currentTimeMillis() / 1000;
            formBody = bodyBuilder
                    .addFormDataPart("accesstoken", UserUtils.getToken(BaseApplication.getContext()))
                    .build();
            request = request.newBuilder().post(formBody).build();
        }

        return request;
    }

    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }

}
